import django_filters
from django.db.models import Q

from .models import Account, Role, AccountRoles


class AccountFilter(django_filters.rest_framework.FilterSet):
    search_key = django_filters.CharFilter(method="filter_search_key")
    username = django_filters.CharFilter(lookup_expr="icontains")
    telephone = django_filters.CharFilter(lookup_expr="icontains")
    realname = django_filters.CharFilter(lookup_expr="icontains")
    role_name = django_filters.CharFilter(method='filter_role_name')
    is_active = django_filters.BooleanFilter()

    @staticmethod
    def filter_search_key(queryset, name, value):
        return queryset.filter(Q(username=value) | Q(realname=value))

    @staticmethod
    def filter_role_name(queryset, name, value):
        # 找出该角色名对应的id
        role_qs = Role.objects.filter(codename=value).values_list('id', flat=True)
        if not role_qs:
            return queryset.none()
        role_id = role_qs[0]
        # 找出该角色的用户
        ids = AccountRoles.objects.filter(role_id=role_id).values_list('account_id', flat=True)
        return queryset.filter(id__in=ids)

    class Meta:
        model = Account
        fields = ['username', 'telephone', 'is_active', 'realname', 'roles']


class RoleFilter(django_filters.rest_framework.FilterSet):

    class Meta:
        model = Role
        fields = ['display', 'level', 'system_name']


class TeacherFilter(django_filters.rest_framework.FilterSet):
    teacher = django_filters.CharFilter(method='get_teacher_filter')

    def get_teacher_filter(self, queryset, name, value):
        return queryset.filter(Q(username=value) | Q(realname__icontains=value))

    class Meta:
        model = Account
        fields = ['teacher', ]
